﻿using System;
using System.Threading.Tasks;
using GrapeCity.Forguncy.Commands;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Ocr.V20181119;
using TencentCloudOcrPlugin.Api;
using TencentCloudOcrPlugin.Resources;

namespace TencentCloudOcrPlugin.Ocr
{
    public abstract class OcrActionBase : TencentCloudApiAction
    {
        protected 
            OcrClient GetClient(TencentCloudApiClientConfig clientConfig)
        {
            var cred = new Credential
            {
                SecretId = clientConfig.SecretId,
                SecretKey = clientConfig.SecretKey
            };
            var clientProfile = new ClientProfile();
            var httpProfile = new HttpProfile
            {
                Endpoint = ("ocr.tencentcloudapi.com")
            };
            clientProfile.HttpProfile = httpProfile;
            return new OcrClient(cred, clientConfig.Region == "nearest" ? "" : clientConfig.Region, clientProfile);
        }
        
        protected async Task<TencentCloudOcrBaseRequest> BuildRequestAsync(OcrBaseProperties properties, IServerCommandExecuteContext dataContext)
        {
            var fileImageObj = await dataContext.EvaluateFormulaAsync(properties?.FileImage);
            var filePath = fileImageObj?.ToString();
            var isNetworkImage = ApiHelper.IsNetworkImagePath(filePath);
            var request = new TencentCloudOcrBaseRequest();
            if (isNetworkImage)
            {
                request.ImageUrl = filePath;
            }
            else
            {
                var array = await ApiHelper.CheckFileTypeAndGetFileBytesAsync(filePath, dataContext);
                request.ImageBase64 = Convert.ToBase64String(array);
            }
            request.IsPdf = ApiHelper.IsPdfFilePath(filePath);
            return request;
        }
    }
}